const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV, // 使用当前环境
});

const db = cloud.database();

// Helper function to generate a new address ID
function generateAddressId() {
  return Math.random().toString(36).substr(2, 9);
}

// 添加或修改地址的主要逻辑
async function addAddress(request) {
  const { userId, addressId, contactName, contactPhone, addressDesc, addressCode, addressDetail, isDefault } = request;
  const userCollection = db.collection('user');

  try {
    // 获取用户信息
    const userRes = await userCollection.where({
      out_user_id: userId
    }).get();

    if (userRes.data.length === 0) {
      console.error("user not found","userId:",userId);
      return {
        code: 404,
        message: 'User not found',
        data: null
      };
    }

    const user = userRes.data[0];
    let addressArray = user.ext_info ? user.ext_info.address || [] : [];

    if (isDefault) {
      // 设置其他地址为非默认
      addressArray = addressArray.map(addr => ({ ...addr, is_default: false }));
    }

    if (addressId) {
      // 修改现有地址
      const index = addressArray.findIndex(addr => addr.address_id === addressId);
      if (index !== -1) {
        addressArray[index] = { 
          address_id: addressId, 
          contact_name: contactName, 
          contact_phone: contactPhone, 
          address_desc: addressDesc, 
          address_code: addressCode, 
          address_detail: addressDetail, 
          is_default: isDefault 
        };
      } else {
        console.error("address not found","addressId:",addressId,"userId:",userId);
        return {
          code: 404,
          message: 'Address not found',
          data: null
        };
      }
    } else {
      // 添加新地址
      addressArray.push({ 
        address_id: generateAddressId(), 
        contact_name: contactName, 
        contact_phone: contactPhone, 
        address_desc: addressDesc, 
        address_code: addressCode, 
        address_detail: addressDetail, 
        is_default: isDefault 
      });
    }

    // 更新用户信息
    await userCollection.doc(user._id).update({
      data: {
        'ext_info.address': addressArray
      }
    });

    return {
      code: 200,
      message: 'success',
      data: null
    };
  } catch (error) {
    console.error("Error:", error.stack || error);
    return {
      code: 500,
      message: 'Error processing request',
      error: error.stack || error.message
    };
  }
}

// 确定用户学校位置的逻辑
function determineUserSchoolByLocation(availableSchoolVoList, longitude, latitude) {
  let defaultLocationSchool = availableSchoolVoList.find(school => school.isDefault === true);
  if (defaultLocationSchool) {
    defaultLocationSchool.matchCurPosition = true;
  }
}

// 查询学校最新优惠券配置
function querySchoolLatestCouponConfig(couponConfigsForSchools, schoolCode) {
  let couponConfigsForCurSchool = couponConfigsForSchools.filter(couponConfig => 
    couponConfig.available_address.find(address => address === schoolCode)
  );
  couponConfigsForCurSchool.sort((config1, config2) => 
    config2.coupon_package_version - config1.coupon_package_version
  );
  return couponConfigsForCurSchool.length > 0 ? couponConfigsForCurSchool[0] : null;
}

// 确定是否显示优惠券包弹窗
async function determineShowCouponPackagePopup(availableSchoolVoList, openId, couponConfigsForSchools) {
  let userCurSchoolVo = availableSchoolVoList.find(school => school.matchCurPosition === true);
  let couponConfigForUserSchool = querySchoolLatestCouponConfig(couponConfigsForSchools, userCurSchoolVo.addressCode);
  if (couponConfigForUserSchool) {
    const couponPackageId = couponConfigForUserSchool.coupon_package_id;
    const couponPackageVersion = couponConfigForUserSchool.coupon_package_version;
    const couponPopupImgUrl = couponConfigForUserSchool.coupon_popup_img_url;
    const couponsResOfCurUser = await db.collection('coupon_record').where({ 
      out_user_id: openId, 
      coupon_package_id: couponPackageId,
      coupon_package_version: couponPackageVersion 
    }).get();
    userCurSchoolVo.showHomePopUp = couponsResOfCurUser.data.length <= 0;
    userCurSchoolVo.couponPackageId = couponPackageId;
    userCurSchoolVo.popupImgUrl = couponPopupImgUrl;
  }
}

// 获取可用学校列表的主要逻辑
async function getAvaliableSchoolList(request) {
  const { openId, longitude, latitude } = request;
  const wxContext = cloud.getWXContext();
  const openIdOrMockOpenId = openId || wxContext.OPENID;

  try {
    // 查询 config 表中 config_name 为 school_list 的记录
    const [availableSchoolListRes, couponConfigsRes] = await Promise.all([
      db.collection('config').where({ config_name: 'school_list' }).get(),
      db.collection('coupon_config').get()
    ]);

    if (availableSchoolListRes.data.length === 0) {
      console.error("School list not found");
      return {
        code: 404,
        message: 'School list not found',
        data: {}
      };
    }

    let availableSchoolVoList = [];
    const availableSchoolList = availableSchoolListRes.data[0].content;
    for (let i = 0; i < availableSchoolList.length; i++) {
      let availableSchoolVo = {};
      availableSchoolVoList.push(availableSchoolVo);
      const availableSchool = availableSchoolList[i];
      availableSchoolVo.addressDesc = availableSchool.address_name;
      availableSchoolVo.addressCode = availableSchool.address_code;
      availableSchoolVo.isDefault = availableSchool.is_default;
    }

    determineUserSchoolByLocation(availableSchoolVoList, longitude, latitude);
    // await determineShowCouponPackagePopup(availableSchoolVoList, openIdOrMockOpenId, couponConfigsRes.data);

    return {
      code: 200,
      message: 'success',
      data: {
        addressList: availableSchoolVoList
      }
    };

  } catch (error) {
    console.error("Error:", error.stack || error);
    return {
      code: 500,
      message: 'Error processing request',
      error: error.stack || error.message
    };
  }
}

module.exports = {
  addAddress: addAddress,
  getAvaliableSchoolList: getAvaliableSchoolList
};
